package com.jwtsecurity.system.serivce.impl;

import com.jwtsecurity.system.serivce.UserinfoService;
import com.jwtsecurity.util.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class JwtService {

    @Resource
    AuthenticationManager authenticationManager;

    @Resource
    UserDetailsService service;

    @Resource
    JwtTokenUtil jwtTokenUtil;

    public Map<String,Object> login(Map<String,Object> map){
        Map<String,Object> res = new HashMap<>();
        if (StringUtils.isEmpty(map.get("username").toString())||StringUtils.isEmpty(map.get("password").toString())){
            res.put("code",5001);
            res.put("msg","用户名或密码不能为空");
            return res;
        }
        try {
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(map.get("username").toString(),map.get("password").toString());
        Authentication authenticate = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            res.put("code",5002);
            res.put("msg","认证失败");
            return res;
        }
        UserDetails userDetails = service.loadUserByUsername(map.get("username").toString());
        res.put("token",jwtTokenUtil.generateToken(userDetails));
        return res;
    }

    public Map<String, Object> refresh(String token) {
        Map<String,Object> res = new HashMap<>();
        if (!jwtTokenUtil.isTokenExpired(token)){
            res.put("token",jwtTokenUtil.refreshToken(token));
            return res;
        }
        res.put("token",null);
        return res;
    }
}
